//
//  OAuthViewController.swift
//  weibo
//
//  Created by RDDBoss3 on 2018/7/9.
//  Copyright © 2018年 Fly. All rights reserved.
//

import UIKit
import SVProgressHUD

// 通过webView加载微博授权页面
class OAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "微博授权登录"
        
        view = webView
        
        webView.delegate = self
        
        webView.scrollView.isScrollEnabled = false
        
        view.backgroundColor = UIColor.white
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", isBackBtn: true, target: self, action: #selector(back))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", isBackBtn: false, target: self, action: #selector(userPsswd))
        
        // 加载授权页
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(RedirectURI)"
        
        guard let url = URL(string: urlStr) else {
           
            return
            
        }
        
        let request = URLRequest(url: url)
        
        webView.loadRequest(request)
        
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @objc fileprivate func back() {
        
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
        
    }
    
    @objc private func userPsswd() {
        
        let js = "document.getElementById('userId').value = '17623878187';" + "document.getElementById('passwd').value = 'wangjimima';"
        
        webView.stringByEvaluatingJavaScript(from: js)
        
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension OAuthViewController: UIWebViewDelegate {
    
    /// webView将要加载请求
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - request: 请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否加载
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    
//        http://baidu.com/?code=e186797b5163a0cbf835850163dd50d7
        // 1.如果请求地址包含 “http://baidu.com” 则不加载页面，反之加载
        let url = request.url
        
        let str = url?.absoluteString
        
        // URL中 “?” 后面的所有部分
        let parameterStr = url?.query
        
        if (str?.hasPrefix(RedirectURI)) == false {
            return true
        }
        
        // 2.从http://baidu.com回调地址的查询字符串中查找 “code=”，如果有，则授权成功，反之，授权失败
        if parameterStr?.hasPrefix("code=") == false {//取消授权
            
            back()
            
            return false
            
        }

        let code = parameterStr?.substring(from: "code=".endIndex) ?? ""
        
        NetworkManager.networkManager.loadAccessToken(code: code) { (isSuccess) in
            
            if isSuccess == true {
                
                // 可不用显示 登录成功
                SVProgressHUD.showSuccess(withStatus: "登录成功")
                
                // 页面跳转
                // 1.发送通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: UserLoginSuccessNotification), object: nil)
                
                // 2.关闭页面
                self.back()
                
            }
            else
            {
                
                SVProgressHUD.showError(withStatus: "网络请求失败")
                
            }
            
        }
        
        print("授权码 --- \(code)")
        
        return false
        
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
